package com.sangmo.fts.training.service;

import com.sangmo.boot.framework.common.errors.ServiceException;
import com.sangmo.boot.framework.common.errors.StandardErrors;
import com.sangmo.boot.framework.common.session.UserSession;
import com.sangmo.fts.teacher.model.Examination;
import com.sangmo.fts.teacher.service.ExaminationService;
import com.sangmo.fts.training.model.Training;
import com.sangmo.fts.user.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
public class TrainingHelper {

    @Autowired
    private TrainingService trainingService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private ExaminationService examinationService;


    public Collection<String> retrieveAccess(Long trainingId) throws ServiceException{
        boolean canAccess = false;
        Training training = trainingService.findOneCache(trainingId);
        Long currentUserId = (Long) UserSession.getUserInterface().getId();

        if (null != training) {

            if (null != training.getExaminationId()) {
                examinationService.checkExamEnterAccess(training.getExaminationId(), currentUserId, training.getTeamId());
            }
            checkTimeRangeValid(training);
            if (Training.Modes.INDIVIDUAL.equals(training.getMode())) {
                canAccess = currentUserId.equals(training.getCreatedBy())? true : false;
                if (!canAccess) {
                    throw new ServiceException(StandardErrors.CLIENT_ERROR.getStatus(), "error.training.access.disabled");
                }
                return permissionService.findUriByApplication(training.getBusinessType());

            } else {
                List<Long> userIds = trainingService.findTeammateUserIdsByTeamId(training.getTeamId());
                canAccess = userIds.contains(currentUserId)? true : false;
                if (!canAccess) {
                    throw new ServiceException(StandardErrors.CLIENT_ERROR.getStatus(), "error.training.access.disabled");
                }
                Set<String> roles = trainingService.findTeammateRolesByTeamIdAndUserId(training.getTeamId(), currentUserId);
                return permissionService.findUriByApplicationAndRoles(training.getBusinessType(), roles);

            }
        }
        throw new ServiceException(StandardErrors.CLIENT_ERROR.getStatus(), "error.training.access.disabled");
    }

    private void checkTimeRangeValid(Training training) {
        if (null != training.getExaminationId()) {
            Date now = new Date();
            if (null != training.getEndTime() && now.compareTo(training.getEndTime()) > 0) {
                throw new ServiceException(StandardErrors.CLIENT_ERROR.getStatus(), "error.training.duration.notvalid");
            }
        }
    }
}
